from config.config import settings  
from modules.code_genrator.enums.column_enums import GenMySQLColumnType, GenPostgreSQLColumnType


def _normalize_sql_type(typing: str) -> str:
    """
    规范化数据库列类型字符串：
    - 去掉长度/修饰（如 varchar(50)、int unsigned）
    - 转为大写，统一别名（如 character varying -> VARCHAR, integer -> INT）
    """
    t = (typing or '').strip().upper()
    # 去掉长度说明
    if '(' in t:
        t = t.split('(')[0].strip()
    # 去掉常见修饰词
    for suffix in [' UNSIGNED', ' ZEROFILL']:
        if t.endswith(suffix):
            t = t[: -len(suffix)]
    # 别名统一
    if t == 'INTEGER':
        t = 'INT'
    if t == 'CHARACTER VARYING':
        t = 'VARCHAR'
    if t == 'BOOL':
        t = 'BOOLEAN'
    return t


def sql_type_to_sqlalchemy(typing: str) -> str:
    """
    将 SQL 类型转换为 SQLAlchemy 类型

    :param typing: SQL 类型字符串
    :return:
    """
    norm = _normalize_sql_type(typing)
    if settings.DATABASE_TYPE == 'mysql':
        if norm in GenMySQLColumnType.get_member_keys():
            return norm
    else:
        if norm in GenPostgreSQLColumnType.get_member_keys():
            return norm
    return 'String'


def sql_type_to_pydantic(typing: str) -> str:
    """
    将 SQL 类型转换为 Pydantic 类型

    :param typing: SQL 类型字符串
    :return:
    """
    norm = _normalize_sql_type(typing)
    try:
        if settings.DATABASE_TYPE == 'mysql':
            return GenMySQLColumnType[norm].value
        return GenPostgreSQLColumnType[norm].value
    except KeyError:
        return 'str'
